/* $Id: ScoreCalculator.java 39 2009-07-24 22:48:06Z h_m_r@gmx.de $ */
package org.jugger.tournament.model.score;

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;

/**
 * @author Sven Hamer
 */
public abstract class ScoreCalculator {

	public int getScoreForTeamA(int pointsTeamA, int pointsTeamB) {
		if(!isFinishable(pointsTeamA, pointsTeamB))
			throw new RuntimeException("Match is not finishable.");

		return getScore(pointsTeamA, pointsTeamB);
	}

	public int getScoreForTeamB(int pointsTeamA, int pointsTeamB) {
		return getScoreForTeamA(pointsTeamB, pointsTeamA);
	}

	public boolean isFinishable(int pointsTeamA, int pointsTeamB) {
		return true;
	}

	public String getPrefix() {
		String className = getClass().getSimpleName();
		return className.substring(0, className.length() - "ScoreCalculator".length());
	}

	protected abstract int getScore(int points, int pointsOpponent);


	public static Collection<ScoreCalculator> getAll() {
		Collection<ScoreCalculator> result = new ArrayList<ScoreCalculator>();
		result.add(new KOScoreCalculator());
		result.add(new TwoPointsScoreCalculator());
		result.add(new ThreePointsScoreCalculator());
		return result;
	}


	protected static HashMap<Class<?>, ScoreCalculator> instances = new HashMap<Class<?>, ScoreCalculator>();
	public static ScoreCalculator getFromPrefix(String prefix) {
		String name = prefix+"ScoreCalculator";
		try {
			Class<?> clazz = Class.forName(ScoreCalculator.class.getPackage().getName()+"."+name);
			return instances.get(clazz);
		} catch (ClassNotFoundException e) {
			// invalid class
		}
		return null;
	}
}
